package com.yyfax.ph.web;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import butterknife.BindView;
import com.yyfax.common.CLog;
import com.yyfax.common.state.StateView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.share.ShareAgent;
import com.yyfax.ph.common.widgets.dialog.BottomGridDialog;
import com.yyfax.ph.home.banner.BannerModel;
import com.yyfax.ph.personal.authority.login.LoginActivity;
import com.yyfax.ph.personal.feedback.FeedBackActivity;

import java.util.ArrayList;
import java.util.List;

public class WebActivity extends BaseYYFaxActivity implements WebPresenter.View , BottomGridDialog.BottomGridItemClickListener{
	private static final String TAG = WebActivity.class.getSimpleName();
	private final static int WEB_LOADER_ID = 102;

	private static final String FLAG_SHOW_SHARE_BTN = "1";
	private static final String wxPackage = "com.tencent.mm";

	public static final String TYPE = "type";
	public static final String TITLE = "title";
	public static final String LINKURL = "linkUrl";
	public static final String INTENT_KEY_BANNER_BEAN = "intent_key_banner_bean";

	private static final int SHARE_TYPE_WECHAT_FRIEND = 0;
	private static final int SHARE_TYPE_CIRCLE = 1;


	/**
	 * 注册协议
	 */
	public static final int TYPE_REGISTRATION_AGREEMENT = 1;
	/**
	 * 公司简介
	 */
	public static final int TYPE_COMPANY_PROFILE = 2;
	/**
	 * 产品描述
	 */
	public static final int TYPE_PRODUCT_DESCRIPTION = 3;

	/**
	 * 银行列表页面
	 */
	public static final int TYPE_BANK_LIST = 5;

	/**
	 * 常见问题
	 */
	public static final int TYPE_COMMON_PROBLEM = 6;
	/**
	 * 推荐服务协议
	 */
	public static final int TYPE_RECOMMEND_SERVICE_PROTOCOL = 7;
	/**
	 * 分享
	 */
	public static final int TYPE_SHARE = 8;


	@BindView(R.id.web_progress_bar)
	ProgressBar mProgressBar;
	@BindView(R.id.web_view)
	WebView mView;
	private StateView mStateView;

	private int mType;
	private String mTitle;

	private WebPresenter mPresenter;
	private String mLinkUrl;
	BottomGridDialog mGridDialog;
	private int[] mDesIds = {R.string.weichat_friend, R.string.weichat_moments};
	private int[] mIconIds = {R.drawable.ic_wechat_friend, R.drawable.ic_wechat_circle};
	private List<BottomGridDialog.ItemBean> mShareItems = new ArrayList<>();
	private BannerModel.BannerBean mBannerBean;
	private ShareAgent mShareAction;

	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	/***
	 *
	 * @param aty
	 * @param title
	 * @param type 获取页面类型 1：注册协议 2：公司简介 3：产品描述 4：计算器 5：银行列表页面 6:常见问题
	 */
	public static void start(Activity aty, String title, int type) {
		Intent i = new Intent(aty, WebActivity.class);
		i.putExtra(WebActivity.TITLE, title);
		i.putExtra(WebActivity.TYPE, type);
		aty.startActivity(i);
	}

	public static void start(Activity aty, String linkUrl) {
		Intent i = new Intent(aty, WebActivity.class);
		i.putExtra(WebActivity.LINKURL, linkUrl);
		aty.startActivity(i);
	}

	public static void start(Activity aty, String linkUrl,String title) {
		Intent i = new Intent(aty, WebActivity.class);
		i.putExtra(WebActivity.LINKURL, linkUrl);
		i.putExtra(WebActivity.TITLE, title);
		aty.startActivity(i);
	}

	public static void start(Activity aty, BannerModel.BannerBean bannerBean) {
		Intent i = new Intent(aty, WebActivity.class);
		i.putExtra(INTENT_KEY_BANNER_BEAN, bannerBean);
		aty.startActivity(i);
	}

	@Override
	protected void onResume() {
		super.onResume();
		hintKeyboard();
	}

	@Override
	public void onBackBtnPressed() {
		if (!canGoBack()) {
			super.onBackBtnPressed();
			finish();
		}
	}

	@Override
	public void onBackPressed() {
		if (!canGoBack()) {
			super.onBackPressed();
			finish();
		}
	}

	private boolean canGoBack() {
		if (mView.canGoBack()) {
			mView.goBack();
			return true;
		}
		return false;
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(WEB_LOADER_ID, null, this);
		setTitle(mTitle);

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
				| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	}

	@Override
	protected void onDestroy() {
		if (mView != null) {
			mView.removeAllViews();
			if (mView.getParent() instanceof ViewGroup) {
				((ViewGroup) mView.getParent()).removeView(mView);
			}
			mView.setTag(null);
			mView.clearHistory();
			mView.clearCache(true);
			mView.destroy();
			mView = null;
		}
		getSupportLoaderManager().destroyLoader(WEB_LOADER_ID);
		super.onDestroy();
		if (mShareAction != null) {
			mShareAction.onDestroy();
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new WebPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (WebPresenter) data;
		mPresenter.attach(this);
		if (TextUtils.isEmpty(mLinkUrl)) {
			mPresenter.getWebUrl(mType);
		} else {
			mView.loadUrl(mLinkUrl);
		}
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
		Intent i = getIntent();
		if (null == i)
			return;

		mType = i.getIntExtra(TYPE, -1);
		mTitle = i.getStringExtra(TITLE);
		mLinkUrl = i.getStringExtra(LINKURL);
		mBannerBean = i.getParcelableExtra(INTENT_KEY_BANNER_BEAN);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.web_activity_layout;
	}

	@Override
	public void initContentView() {
		setupTopBar(null, true, false, true, true);
		initWebSettings();
		if (TYPE_COMMON_PROBLEM == mType){
			setBtnRightVisible(true);
			setBtnRightTx(R.string.question_feed_back);
		}
		if (mBannerBean != null && !TextUtils.isEmpty(mBannerBean.href)){
			mLinkUrl = mBannerBean.href;
			if (TextUtils.equals(mBannerBean.isRepost, FLAG_SHOW_SHARE_BTN)){
				setTopBarBackgroundColor(ContextCompat.getColor(this, R.color.color_000000));
				setBtnBackBackground(R.drawable.exit_icon_white);
				setTitleCenterColor(getResources().getColor(R.color.color_white));
				setRightImageBtnVisible(true);
				setRightImageBtnSrc(R.drawable.icon_btn_share, R.color.transparent);
				mShareAction = new ShareAgent(this, mBannerBean.href, mBannerBean.wxTitle, mBannerBean.wxContent, null);
				mType = TYPE_SHARE;
			}else {
				setRightImageBtnVisible(false);
			}
		}

		mStateView = StateView.inject((RelativeLayout) mView.getParent(), false);
		mStateView.setEmptyResource(R.layout.state_view_no_data);
		mStateView.setErrorResource(R.layout.state_view_no_network);
		mStateView.setOnErrorClickListener(new StateView.OnErrorClickListener() {
			@Override
			public void onErrorClick() {
				mStateView.showContent();
				if (TextUtils.isEmpty(mLinkUrl)) {
					mPresenter.getWebUrl(mType);
				}else {
					mView.loadUrl(mLinkUrl);
				}
			}
		});
	}

	private void initWebSettings() {
		WebSettings settings = mView.getSettings();
		mView.getSettings().setBuiltInZoomControls(true);// make sure your pinch zoom is enabled
		mView.getSettings().setDisplayZoomControls(false);// don't show the zoom controls
		settings.setSupportZoom(true);// 设置可以支持缩放
		settings.setUseWideViewPort(true);// 扩大比例的缩放
		settings.setJavaScriptEnabled(true);
		settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);// 自适应屏幕
		settings.setLoadWithOverviewMode(true);
		mView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				CLog.i(TAG, url);
				if (!TextUtils.isEmpty(url)) {
					if (url.trim().equalsIgnoreCase("target:recommend")) {
						goToRecommend();
					} else {
						if (url.contains("yy://"))
							return false;
						else
							view.loadUrl(url);
					}
					return true;
				}
				return false;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				mProgressBar.setVisibility(View.VISIBLE);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mProgressBar.setVisibility(View.GONE);
				if(TextUtils.isEmpty(mTitle)) {
					setTitle(mView.getTitle());
				}else{
					setTitle(mTitle);
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				onFunctionalError(null, false);
			}
		});
		mView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				super.onProgressChanged(view, progress);
				mProgressBar.setProgress(progress);
				CLog.i(TAG, progress + "");
			}
		});
	}

	public void goToRecommend() {
//		MainActivity.startToHomeFragment(this);
	}

	@Override
	public void onRightBtnPressed() {
		if(mType == TYPE_COMMON_PROBLEM) {
			if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
				LoginActivity.start(this);
				return;
			}
			FeedBackActivity.start(this);
		}
	}

	@Override
	public void onRightImgPressed() {
		if (mType == TYPE_SHARE){
			showDialog();
		}
	}

	@Override
	public void getUrlSuccess(String url) {
		mView.setVisibility(View.VISIBLE);
		mLinkUrl = url;
		dismissLoading();
		mView.loadUrl(url);
		CLog.i(TAG, "getUrlSuccess: ");
	}

	@Override
	public void getUrlFailure() {
		dismissLoading();
		CLog.i(TAG, "getUrlFailure: ");
		checkStatus();
	}

	private void checkStatus() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mStateView != null) {
					mView.setVisibility(View.GONE);
					mStateView.showError();
				}
			}
		});
	}

	// TODO: 2017/3/18 没有网络的情况下需要添加空白页
	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		checkStatus();
	}

	private boolean isAvailable(Context ctx, String packageName) {
		final PackageManager pkgMgr = ctx.getPackageManager();
		List<PackageInfo> info = pkgMgr.getInstalledPackages(0);
		for (int i = 0; i < info.size(); i++) {
			if (info.get(i).packageName.equalsIgnoreCase(packageName))
				return true;
		}
		return false;
	}

	@Override
	public void onBottomGridItemClick(AdapterView<?> parent, View view, int type, long id) {
		switch (type){
			case SHARE_TYPE_WECHAT_FRIEND:
				mGridDialog.dismiss();
				if (!isAvailable(this, wxPackage)) {
					showToast(R.string.application_not_installed);
					return;
				}
				if (null != mShareAction) {
					String title = mBannerBean.wxTitle;
					String content = mBannerBean.wxContent;
					mShareAction.setTitle(title);
					mShareAction.setContent(content);
					ShareAgent.getmShareActionListener().resetTitleAndContent(title, content);
					mShareAction.sharePlantForm(ShareAgent.ShareAction.WX_FRIEND, R.drawable.ic_share_app);
				}
				break;
			case SHARE_TYPE_CIRCLE:
				mGridDialog.dismiss();
				if (!isAvailable(this, wxPackage)) {
					showToast(R.string.application_not_installed);
					return;
				}
				if (null != mShareAction) {
					String title = mBannerBean.wxTitle;
					String content = mBannerBean.wxContent;
					mShareAction.setTitle(title);
					mShareAction.setContent(content);
					ShareAgent.getmShareActionListener().resetTitleAndContent(title, content);
					mShareAction.sharePlantForm(ShareAgent.ShareAction.WX_CIRCLE, R.drawable.ic_share_app);
				}
				break;
				default:
					break;
		}
	}

	private void showDialog() {
		if (mGridDialog == null) {
			if (mShareItems.size() <= 0) {
				mShareItems.add(new BottomGridDialog.ItemBean(SHARE_TYPE_WECHAT_FRIEND, mDesIds[0], mIconIds[0])); // 微信分享
				mShareItems.add(new BottomGridDialog.ItemBean(SHARE_TYPE_CIRCLE, mDesIds[1], mIconIds[1])); // 朋友圈
			}

			BottomGridDialog.Builder builder = new BottomGridDialog.Builder(this,
					R.layout.dialog_share_wechat, R.layout.item_dialog_share_wechat);
			mGridDialog = builder.setData(mShareItems)
					.setNegativeButton(getString(R.string.cancel),
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							})
					.setOnItemClickListener(this)
					.create();
			mGridDialog.setCanceledOnTouchOutside(true);
		}
		mGridDialog.show();
	}

	private void hintKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null && imm.isActive() && getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
}
